package com.njbdqn.air.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.njbdqn.air.domain.Air;
import com.njbdqn.air.services.AirService;
import com.njbdqn.componses.bean.PageBean;
import com.njbdqn.componses.bean.PageParam;

@Controller
public class InitController {
	@Autowired
	private AirService airService;
	@Autowired
	private PageParam pip;
	
	@InitBinder
	public void dateBind(ServletRequestDataBinder bind){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		df.setLenient(true);
		bind.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
	}
	
	@RequestMapping("/init.do")
	public ModelAndView init(@RequestParam(required=false)String areaname,@RequestParam(defaultValue="1",required=false)int cp,ModelAndView mav){
		pip.setCurrentPage(cp);
		if(areaname!=null && areaname!=""){
			pip.setCond(areaname);
			mav.addObject("cond",areaname);
		}
		mav.setViewName("index");
		PageBean<Air> pb = airService.findBean(pip);
		if(pb.getData().isEmpty()){
			pb = null;
		}
		mav.addObject("pb", pb);
		mav.addObject("area", airService.findAllArea());
		return mav;
	}
	
	@RequestMapping("/save.do")
	public ModelAndView save(Air air,ModelAndView mav){
		airService.saveAir(air);
		mav.setViewName("redirect:/init.do");
		return mav;
	}
	
	@RequestMapping("/del.do")
	public ModelAndView del(int airid,ModelAndView mav){
		airService.deleteAir(airid);
		mav.setViewName("redirect:/init.do");
		return mav;
	}
	
	@RequestMapping("/update.do")
	public ModelAndView update(Air air,ModelAndView mav){
		airService.updateAirInfo(air);
		mav.setViewName("redirect:/init.do");
		return mav;
	}
	
	@RequestMapping("/single.do")
	public ModelAndView single(int airid,ModelAndView mav){
		mav.setViewName("update");
		mav.addObject("info", airService.findById(airid));
		return mav;
	}
}
